package com.ruoyi.system.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.config.AmapConfig;
import com.ruoyi.system.domain.vo.LocationByIpVO;
import com.ruoyi.system.service.IAmapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @ClassName AmapServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author luqian
 * @Date 2024/6/27 2:13 PM
 * @Copyright 八维
 * @Version V1.0.0
 */
@Service
public class AmapServiceImpl implements IAmapService {
    
    @Autowired
    private AmapConfig amapConfig;


    /**
     * @Description: 看这个高德的文档 调用高德的第三方接口
     * @Param: [ip]
     * @Return: com.ruoyi.common.core.web.domain.AjaxResult
     * @Author: luqian
     * @Date: 2024/6/27 2:16 PM
     */
    @Override
    public AjaxResult getLocationByIp(String ip) {




        //调用之前先做代码的健壮性校验
        if(StringUtils.isEmpty(ip)){
            return AjaxResult.error("ip不能为空");
        }
        if(!Validator.isIpv4(ip)){
            return AjaxResult.error("ip格式不正确");
        }



        //1。请求地址
        //2。请求参数
        //3。请求方式
        //4。响应结果
        //https://restapi.amap.com/v3/ip?ip=114.247.50.2&output=xml&key=<用户的key>




        String locationByIpUrl = amapConfig.getLocationByIpUrl();
        Map<String, Object> params = new HashMap<>();
        params.put("ip",ip);
        params.put("key",amapConfig.getKey());
        String result = HttpUtil.get(locationByIpUrl, params);


        if(!StringUtils.isEmpty(result)){
            //result是一个json，需要解析json，获取省和市

            //第一种写法

          // JSONObject jsonObject = JSONUtil.parseObj(result);
//            if(jsonObject.get("status").toString().equals("0")){
//                return AjaxResult.error("ip解析失败");
//            }
//            String province = jsonObject.get("province").toString();
//            String city = jsonObject.get("city").toString();
            //第二种写法 (推荐)
            LocationByIpVO locationByIpVO = JSONUtil.toBean(result, LocationByIpVO.class);
            String format = String.format("%s-%s", locationByIpVO.getProvince(), locationByIpVO.getCity());
            return AjaxResult.success(locationByIpVO);
        }
         return AjaxResult.error("ip解析失败");
    }

    @Override
    public String test(Integer userId) {
        return null;
    }
}
